#include"stm32f1_init.h"

void gpio_init()
{
	RCC->APB2ENR |= 0x00000001;
	RCC->APB2ENR|=0X0000001e;
	RCC->APB1ENR|=1<<14;
	GPIOB->CRH=0X00;
	GPIOB->CRL=0X00;
	GPIOB->CRH|=0xbu<<28;
	GPIOB->CRH|=0x4u<<24;
	GPIOB->CRH|=0xbu<<20;
	GPIOB->CRL=0x33333303;
	GPIOA->ODR |=1<<8;
	GPIOA->CRH=0x333334b3;
	GPIOA->CRL=0xbbb33333;
	//GPIOA->CRL=0x33333333;
	GPIOA->ODR|=0x7<<5;
	GPIOA->BSRR=1<<5;
}

void SPI2_INIT()
{
    RCC->APB2ENR|=1<<2;
	RCC->APB1ENR|=1<<14;
	SPI2->CR1=(1<<9)|(1<<8)|(1<<6)|(1<<2)|(0<<0)|(5<<3);
}

unsigned char  SPI2_ReadWrites(unsigned char data)
{
	unsigned char timeout=255;
	while(((SPI2->SR)&(1<<7))){
		//user_printf("*\r\n");
		timeout--;
		if(timeout==0){
			return 0xff;
		}
		
	}
	SPI2->DR=data;
	SPI2->CR1&=~(1<<12);
	timeout=255;
	while(((SPI2->SR)&(1<<7))){
		timeout--;
		if(timeout==0){
			return 0xff;
			//user_printf("time out\r\n");
		}
	}
	return SPI2->DR;
}

void RCC_DeInit(void)
{									   
	RCC->APB2RSTR = 0x00000000;//外设复位			 
	RCC->APB1RSTR = 0x00000000;   	  
  	RCC->AHBENR = 0x00000014;  //flash时钟,闪存时钟使能.DMA时钟关闭	  
  	RCC->APB2ENR = 0x00000000; //外设时钟关闭.			   
  	RCC->APB1ENR = 0x00000000;   
	RCC->CR |= 0x00000001;     //使能内部高速时钟HSION	 															 
	RCC->CFGR &= 0xF8FF0000;   //复位SW[1:0],HPRE[3:0],PPRE1[2:0],PPRE2[2:0],ADCPRE[1:0],MCO[2:0]					 
	RCC->CR &= 0xFEF6FFFF;     //复位HSEON,CSSON,PLLON
	RCC->CR &= 0xFFFBFFFF;     //复位HSEBYP	   	  
	RCC->CFGR &= 0xFF80FFFF;   //复位PLLSRC, PLLXTPRE, PLLMUL[3:0] and USBPRE 
	RCC->CIR = 0x00000000;     //关闭所有中断
}
void USART1_Init(void)
{	
	RCC->APB2ENR |=0x1<<14;
	// USART1->BRR=234<<4;
	// USART1->BRR|=6;

	USART1->BRR=19<<4;
	USART1->BRR|=8;
	USART1->CR1=0X202c;
	//USART1->CR2=1<<11;
	//USART1->|=
}

/*------------------------------------------------------------
                  外部12M,则得到72M的系统时钟
------------------------------------------------------------*/	
void Stm32_Clock_Init(void)
{
	unsigned char temp=0;
	unsigned char timeout=0;
	RCC_DeInit();
	RCC->CR|=0x00010000;  //外部高速时钟使能HSEON

	timeout=0;
	while(!(RCC->CR>>17)&&timeout<200)timeout++;//等待外部时钟就绪	 

	//0-24M 等待0;24-48M 等待1;48-72M等待2;(非常重要!)	   
	FLASH->ACR|=0x32;//FLASH 2个延时周期

	RCC->CFGR|=0X002B2400;//APB1/2=DIV2;AHB=DIV1;PLL=12*(CLK/2);HSE作为PLL时钟源
	RCC->CR|=0x01000000;  //PLLON

	timeout=0;
	while(!(RCC->CR>>25)&&timeout<200)timeout++;//等待PLL锁定

	RCC->CFGR|=0x00000002;//PLL作为系统时钟
	while(temp!=0x02&&timeout<200)     //等待PLL作为系统时钟设置成功
	{   
		temp=RCC->CFGR>>2;
		timeout++;
		temp&=0x03;
	}  
}